package org.opens.javaskill.design.apply;

import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * @Date 2020/9/20 21:07
 * @Created by 99126
 */
public class ThreadPreMessagePattern {

    public static void main(String[] args) {

    }

}

class Message {

    private final String value;

    public Message(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

}

class MessageHandler {

    private final static Executor executor = Executors.newFixedThreadPool(5);

    private final static Random random = new Random(System.currentTimeMillis());

    public void request(Message message) {
        executor.execute(() -> {
            String value = message.getValue();
            try {
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("the message will handle by " + Thread.currentThread().getName());
        });
    }

    public void shutdown() {
        // 执行shutdown并不会使线程池立马停止, 而是等待正在工作的线程停止执行任务之后才会停止.
        ((ExecutorService) executor).shutdown();
    }

}

/**
 * 说明:
 * <pre>
 *     1. 这种设计莫是的核心里面是为每一个连接进来的请求单独分配一个线程进行处理.
 *      - 这种单独分配一个线程可以优化为使用线程池, 因为线程的创建和销毁是比较消耗资源的, 使用线程池可以有效避免频繁的创建与销毁.
 * </pre>
 */
class PreThreadClient {

    public static void main(String[] args) {
        MessageHandler handler = new MessageHandler();
        IntStream.rangeClosed(0, 10).forEach(i -> {
            handler.request(new Message("消息" + i));
        });
        handler.shutdown();
    }

}